﻿using UnityEngine;

/// <summary>
/// 生成球体网格
/// </summary>
public class MeshBall : MonoBehaviour {

    static int baseColorId = Shader.PropertyToID("_BaseColor"), // 颜色
        metallicId = Shader.PropertyToID("_Metallic"), // 金属质感
        smoothnessId = Shader.PropertyToID("_Smoothness"); // 表面光滑度


    [SerializeField]
    Mesh mesh = default; // 网格

    [SerializeField]
    Material material = default; // 材质
    
    Matrix4x4[] matrices = new Matrix4x4[1023]; // 变换矩阵
    Vector4[] baseColors = new Vector4[1023]; // 颜色
    float[]
        metallic = new float[1023],
        smoothness = new float[1023];

    MaterialPropertyBlock block;
    
    void Awake () 
    {
        // 随机生成矩阵、颜色
        for (int i = 0; i < matrices.Length; i++) 
        {
            matrices[i] = Matrix4x4.TRS(
                Random.insideUnitSphere * 10f,
                Quaternion.Euler(Random.value * 360f, Random.value * 360f, Random.value * 360f),
                Vector3.one * Random.Range(0.5f, 1.5f)
            );
            
            baseColors[i] = new Vector4(Random.value, Random.value, Random.value, Random.Range(0.5f, 1f));
            metallic[i] = Random.value < 0.25f ? 1f : 0f;
            smoothness[i] = Random.Range(0.05f, 0.95f);
        }
    }
    
    void Update () 
    {
        if (block == null) {
            block = new MaterialPropertyBlock();
            block.SetVectorArray(baseColorId, baseColors);
            block.SetFloatArray(metallicId, metallic);
            block.SetFloatArray(smoothnessId, smoothness);
        }
        
        // GPU实例化
        Graphics.DrawMeshInstanced(mesh, 0, material, matrices, 1023, block);
    }
}